package cn.hackcloud.mutithread.juc;

import java.util.concurrent.CountDownLatch;

/**
 * 闭锁，在完成某些运算时，只有其他线程的运算全部完成，当前运算才继续执行
 * 
 * @author hackcloud
 *
 */
public class TestCountDownLatch {
	public static void main(String[] args) throws Exception {
		final CountDownLatch latch = new CountDownLatch(10);
		LatchDemo latchDemo = new LatchDemo(latch);
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			new Thread(latchDemo).start();

		}
		latch.await();
		long end = System.currentTimeMillis();
		System.out.println("耗时时间为:" + (end - start));
	}
}

class LatchDemo implements Runnable {
	private CountDownLatch latch;

	public LatchDemo(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {
		synchronized (this) {
			try {
				for (int i = 0; i < 5000; i++) {
					if (i % 2 == 0) {
						System.out.println(i);
					}

				}
			} finally {
				latch.countDown();
			}
		}

	}

}